package com.haruhinav.interecptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haruhinav.Utils.JWTUtils;
import com.haruhinav.entity.vo.ResultVO;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ResultVO result = new ResultVO();
        String at = request.getHeader("at");
        try {
            JWTUtils.verify(at);
            if(JWTUtils.fromTokenGetAdmin(request) != 1){
                result.setCode(-6);
                result.setMsg("你不是管理员！");
                result.setType("warning");
                String json = new ObjectMapper().writeValueAsString(result);
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.getWriter().print(json);
                return false;
            }
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();

            result.setCode(-5);
            result.setMsg("无效签名");
            result.setType("error");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            result.setCode(-4);
            result.setMsg("token已过期");
            result.setType("error");
        }catch(AlgorithmMismatchException e){
            e.printStackTrace();
            result.setCode(-3);
            result.setMsg("token算法不一致");
            result.setType("error");
        }catch (NullPointerException e){
            e.printStackTrace();
            result.setCode(-2);
            result.setMsg("无token");
            result.setType("error");
        }
        catch(Exception e){
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg("无效token");
            result.setType("error");
        }
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().print(json);
        return false;
    }
}
